<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use Overtrue\Wechat\Server;
use Overtrue\Wechat\Message;
use App\Http\Controllers\Auth\YRDauth;
use Overtrue\Wechat\Menu;
use Overtrue\Wechat\MenuItem;
use Overtrue\Wechat\User;
use Log;
use Illuminate\Support\Facades\Session;
use DB;
use Overtrue\Wechat\Auth;
use App\UserRepository;
use Auth as Auth2;
use Config;
use Overtrue\Wechat\Stats;

class WechatController extends Controller
{
    /**
     * 处理微信的请求消息
     * @param Server $server
     * @return mixed
     */

    public function serve(Server $server, YRDauth $yrdauth, User $user)
    {
        Log::info(file_get_contents('php://input'));
        // 接受消息
        $server->on('message', function($message) use($yrdauth,$user){
            Log::info('all message:'.$message);
            // 验证openid 绑定过没有
            $openid = $message->FromUserName;
            Log::info('openid:'.$openid);

            Log::info($message->Content);

            return "欢迎关注风景宜人！";
        });


        // 监听关注事件
        $server->on('event', 'subscribe', function($event) use($yrdauth,$user){
            // openid: $event['FromUserName']

            // 记录用户
            $isValid = $this->testUser($event['FromUserName'], $event, $yrdauth, $user);
            if(!empty($isValid)) {
                return $isValid;
            }

//            // 验证用户是否有效 $event['FromUserName']
//            $isValid = $this->checkUserValid($event['FromUserName']);
//            if($isValid) {
//                //已经认证过
//                return Message::make('text')->content($isValid['nickname']."欢迎您再次回来!");
//            }
//            return Message::make('text')->content("为确保公司信息安全，\n请<a href='".Config::get('wechat.siteroot')."/wxauthorize'>点击这里</a>您先验证身份信息" );
        });

        // 捕获菜单点击事件
        $server->on('event', 'click', function($event) use($yrdauth,$user) {
            Log::info('点击菜单所获取的内容：'.$event);
            // 验证openid 绑定过没有
            $openid = $event->FromUserName;
            Log::info('openid:'.$openid);

            // 验证用户
            $isValid = $this->testUserBand($openid, $event, $yrdauth, $user);
            if(!empty($isValid)) {
                return $isValid;
            }

            //验证环节end,继续关键字逻辑
            Log::info('菜单 EventKey:'.$event->EventKey);

            // 查找回复类型 text image news
            $res_reply = DB::table('autoreplys')->where('keyword', $event->EventKey)->get();

            foreach($res_reply as $reply) {Log::info('type:'. $reply->type);
                if($reply->type == 'text') {
                    Log::info('文本类型');
                    // 文本回复
                    return Message::make('text')->content($reply->content);
                }else if ($reply->type == 'image') {
                    // 图片回复
                    Log::info('图片类型'. $reply->media_id);
                    return Message::make('image')->media($reply->media_id);
                }else if ($reply->type == 'news') {
                    // 图文回复
                    Log::info('图文类型'. $reply->media_id);
                    Log::info('图文media_id:'. $reply->media_id);
                    // 获取图文详细内容
                    $newsInfo = DB::table('news')->where('media_id', $reply->media_id)->get();
                    Log::info($newsInfo);
                    foreach($newsInfo as $key=>$item) {
                        // 图文中缩略图图片地址
                        $picInfo = DB::table('picuploads')->where('media_id', $item->thumb_media_id)->get();

                        $newsArr[] = Message::make('news_item')->title($item->title)->description($item->digest)->url($item->url)->picUrl($picInfo[0]->weixinurl);
                    }

                    $news = Message::make('news')->items(function() use($newsArr){
                        //Log::info($newsArr);
                        return $newsArr;
                    });
                    return $news;
                }
            }

        });



        return $server->serve(); // 或者 return $server;
    }

    /**
     * 检查用户是否有效
     * @param $openid
     */

    public function checkUserValid($openid) {
        // 查找数据库，是否存在
        $find_result = DB::table('user_record')->where('openid', $openid)->first();
        if(empty($find_result)) {
            return false;
        }else {
            return $find_result;
        }
    }


    /**
     * 微信后台首页
     */
    public function index() {
        $data = [];
        Log::info('进入后台首页');
        $data['rand'] = mt_rand(1,4);
        if(is_pjax()) {
            return View('admin.indexsegment', $data);
        }
        return View('admin.index', $data);
    }



    /**
     * 验证用户是否存在
     * @param $openid
     * @param $message
     * @param $yrdauth
     * @param $user
     * @return mixed
     */
    private function testUser($openid, $message, $yrdauth, $user) {
        $isValid = $this->checkUserValid($openid);
        if(!$isValid) {
            // 用户不存在

            // 根据openid 获取用户信息并数据库写入绑定记录
            Log::info('openid:'. $openid);
            $userinfo = $user->get($openid);
            Log::info($userinfo);

            $id = DB::table('user_record')->insertGetId(
                [
                    'openid' => $openid,
                    'nickname' => $userinfo->nickname,
                    'sex' => $userinfo->sex,
                    'city' => $userinfo->city,
                    'country' => $userinfo->country,
                    'province' => $userinfo->province,
                    'language' => $userinfo->language,
                    'headimgurl' => $userinfo->headimgurl,
                    'subscribe_time' => $userinfo->subscribe_time,
                    'unionid' => $userinfo->unionid,
                    'isband' => 0
                ]
            );
            if($id) {
                return Message::make('text')->content("欢迎您的到来!" );
            }
        }else {
            return Message::make('text')->content("欢迎您再次的到来!" );
        }
    }


    /**
     * 验证用户绑定
     * @param $openid
     * @param $message
     * @param $yrdauth
     * @param $user
     * @return mixed
     */
    private function testUserBand($openid, $message, $yrdauth, $user) {
        $isValid = $this->checkUserValid($openid);
        if(!$isValid->isband) {
            // 用户未绑定

            Log::info('openid:'. $openid);
            $userinfo = $user->get($openid);
            Log::info($userinfo);

            return Message::make('text')->content("为确保公司信息安全，\n请<a href='".Config::get('wechat.siteroot')."/wxauthorize'>点击这里</a>您先验证身份信息" );
        }else {
            return false;
        }
    }

    /**
     * 公众号验证
     */
    public function wxauthorize(Auth $auth) {
        $logged_user = Session::get('logged_user');
        if(empty($logged_user)) {
            $user = $auth->authorize($to = null, $scope = 'snsapi_userinfo', $state = 'STATE');
            Session::set('logged_user', $user);
            Log::info('授权成功，获取用户信息：'.$user);
        }else {
            $user = Session::get('logged_user');
        }

        $userInfo = json_decode($user);

        $data['openid'] = $userInfo->openid;
        $data['nickname'] = $userInfo->nickname;
        $data['sex'] = $userInfo->sex;
        $data['city'] = $userInfo->city;
        $data['country'] = $userInfo->country;
        $data['province'] = $userInfo->province;
        $data['language'] = $userInfo->language;
        $data['headimgurl'] = $userInfo->headimgurl;


        return View('wxauthorize', $data);
    }

    public function wxcheck(Request $request, YRDauth $yrdauth) {

        Log::info('my_openid:'. $request->get('openid'));

        $email = trim($request->get('email'));
        $password = trim($request->get('password'));

        if(empty($email) || empty($password)) {
            return redirect('/wxauthorize')
                ->withInput($request->only('email', 'remember'))
                ->withErrors([
                    'email' => '账户或密码不能为空',
                ]);
        }

        // yrd 内部验证
        //$res = $yrdauth->checkYrdUser($request->input('email'),$request->input('password'));
        $res = 1;

        if($res == 1) {
            // ldap验证通过

            $isValid = $this->checkUserValid($request->get('openid'));
            if($isValid) {
                // 存在
                Log::info('更新用户信息为已绑定');
                // 更新用户
                $id = DB::table('user_record')->where('openid', $request->get('openid'))->update(
                    [
                        'isband' => 1
                    ]
                );

                Log::info('验证通过');
                // 跳转认证成功页面
                return View('authorize_success');

            }

        }else{
            return redirect('/wxauthorize')
                ->withInput($request->only('email', 'remember'))
                ->withErrors([
                    'email' => '账户或密码不正确',
                ]);
        }


    }


    protected function validator(array $data)
    {
        return Validator::make($data, [
            'email' => 'required|email|max:255',
            'password' => 'required|confirmed|min:6',
        ]);
    }

}
